/**
 * 倒计时Hook（uniapp适配版）
 * @returns {Object} 包含倒计时值和操作方法
 */
const useCountDown = () => {
  const counter = ref(0)
  const interval = ref(null)
  const isRunning = ref(false)
  const instance = getCurrentInstance()

  const startCountDown = (num) => {
    if (isRunning.value) {
      console.warn('倒计时已在运行中')
      return
    }
    
    const count = Math.max(0, parseInt(num))
    if (isNaN(count)) {
      console.error('倒计时参数必须是数字')
      return
    }
    
    counter.value = count
    isRunning.value = true
    
    clearCountDown()
    
    // 使用uniapp的定时器API
    interval.value = setInterval(() => {
      if (counter.value <= 0) {
        clearCountDown()
        return
      }
      counter.value--
    }, 1000)
  }

  const clearCountDown = () => {
    if (interval.value) {
      clearInterval(interval.value)
      interval.value = null
      isRunning.value = false
    }
  }

  const resetCountDown = (num) => {
    clearCountDown()
    const count = Math.max(0, parseInt(num))
    counter.value = isNaN(count) ? 0 : count
  }

  // 页面卸载时自动清除定时器
  onUnmounted(() => {
    clearCountDown()
    // 小程序环境额外处理
    if (instance?.proxy?.$scope?.onUnload) {
      instance.proxy.$scope.onUnload = () => clearCountDown()
    }
  })

  return { 
    counter, 
    isRunning,
    startCountDown, 
    clearCountDown,
    resetCountDown
  }
}

export { useCountDown }